package com.ai.module.business.controller;

import com.ai.module.chat.common.ano.NoAuth;
import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.domain.BasePage;
import com.ai.module.chat.common.enu.MjPrompt;
import com.ai.module.chat.config.ChatImageBo;
import com.ai.module.user.domain.req.UserTalkReq;
import com.ai.module.user.domain.vo.UserPromptVo;
import com.ai.module.user.service.ChatService;
import com.ai.module.user.service.UserPromptService;
import com.ai.module.mj.service.TranslateService;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.theokanning.openai.completion.CompletionRequest;
import com.theokanning.openai.finetune.FineTuneRequest;
import com.theokanning.openai.image.CreateImageEditRequest;
import com.theokanning.openai.image.CreateImageVariationRequest;
import com.theokanning.openai.image.Image;
import com.theokanning.openai.image.ImageResult;
import io.github.asleepyfish.enums.chat.RoleEnum;
import io.github.asleepyfish.enums.image.ImageResponseFormatEnum;
import io.github.asleepyfish.enums.image.ImageSizeEnum;
import io.github.asleepyfish.util.OpenAiUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**

 * @author: MrHeg
 * @create: 2023-09-01 20:36
 * @description:
 **/
@Slf4j
@RestController
@RequestMapping("/member/chat")
@Api(tags = "用户chatgpt聊天")
public class MangeChatController {

    @Resource(name = "chat4Service")
    private ChatService mangeChatService;

    @Resource(name = "chat4Service")
    private ChatService chat3Service;

    @GetMapping("/talkMange")
    @ApiOperation(value = "用户聊天,流式返回管理台", hidden = true)
    public void talkMange(String message) {
        mangeChatService.talkMange(message);
    }

    @GetMapping("/gptDalla3")
    @ApiOperation(value = "用户聊天,流式返回管理台", hidden = true)
    public List<String> gptDalla3(String imageDesc) {
        return mangeChatService.createImage(imageDesc);
    }

    //createImage
    @GetMapping("/talkVue")
    @NoAuth
    @ApiOperation(value = "用户聊天,流式返回web", notes = "后期采用 webSocket")
    public void talkVue(@ApiParam("用户话术") String message, @ApiParam("聊天的AI") String robotId, @ApiParam("AI类型 CHAT_4/其它") String robotType, HttpServletResponse response) throws IOException {
        UserTalkReq userTalkReq = new UserTalkReq();
        userTalkReq.setMessage(message);
        userTalkReq.setRobotId(robotId);
        userTalkReq.setUserId(ThreadLocalContext.getUserId());
        if (!"CHAT_4".equalsIgnoreCase(robotType)) {
            chat3Service.talkVue(userTalkReq, response);
            return;
        }
        chat3Service.talkVue(userTalkReq, response);
    }

    @GetMapping("/voice2Text")
    @ApiOperation(value = "", hidden = true)
    public String transferVoice(MultipartFile file) {
        return mangeChatService.voice2Text(file);
    }


    @GetMapping("/voice2English")
    @ApiOperation(value = "", hidden = true)
    public String voice2English(MultipartFile file) {
        return mangeChatService.voice2English(file);
    }

    @GetMapping("/createImageEdit")
    @ApiOperation(value = "", hidden = true)
    public void createImageEdit() {
        CreateImageEditRequest createImageEditRequest = CreateImageEditRequest.builder().prompt("Background changed to red")
                .n(1).size(ImageSizeEnum.S512x512.getSize()).responseFormat(ImageResponseFormatEnum.URL.getResponseFormat()).build();
        ImageResult imageEdit = OpenAiUtils.createImageEdit(createImageEditRequest, "D:\\code\\2023\\chatGpt\\springboot-openai-chatgpt\\mrhe-webscoket\\chat_business\\src\\main\\resources\\image\\1\\loadCookie.png", "D:\\code\\2023\\chatGpt\\springboot-openai-chatgpt\\mrhe-webscoket\\chat_business\\src\\main\\resources\\image\\1\\mask.png");
        List<Image> data = imageEdit.getData();
        System.out.println("data = " + data);
        System.out.println("图片编辑结果：" + imageEdit);
    }

    @GetMapping("/createImageVariation")
    @ApiOperation(value = "", hidden = true)
    public List<Image> createImageVariation() {
        CreateImageVariationRequest createImageVariationRequest = CreateImageVariationRequest.builder()
                .n(2).size(ImageSizeEnum.S512x512.getSize()).responseFormat(ImageResponseFormatEnum.URL.getResponseFormat()).build();
        ImageResult imageVariation = OpenAiUtils.createImageVariation(createImageVariationRequest,
                "D:\\code\\2023\\chatGpt\\springboot-openai-chatgpt\\mrhe-webscoket\\chat_business\\src\\main\\resources\\image\\1\\loadCookie.png");
        System.out.println("图片变体结果：" + imageVariation);
        return imageVariation.getData();
    }

    static final String PATH =
            "C:\\Users\\14550\\Desktop\\commitment.docx";

    //"https://mrhe-ai-test.oss-cn-shenzhen.aliyuncs.com/test/commitment.docx?Expires=1709504680&OSSAccessKeyId=TMP.3KirpZkkDinnAHtccGedGfdF289eyYghCb6hDKPcQKaRoP7tTvVTXxxMem2NnLUiMqhE6nq6HCVoUJxLokkG95B9EkZrXP&Signature=Lm6p5ApqhGATGUsT66oD%2B1k9uPE%3D";
    @GetMapping("/fileTune")
    @ApiOperation(value = "", hidden = true)
    public void fileTune() {
        // 创建微调
        FineTuneRequest fineTuneRequest = FineTuneRequest.builder().trainingFile("").build();
        System.out.println("创建微调信息：" + OpenAiUtils.createFineTune(fineTuneRequest));
        // 创建微调完成
        CompletionRequest completionRequest = CompletionRequest.builder().build();
        System.out.println("创建微调完成信息：" + OpenAiUtils.createFineTuneCompletion(completionRequest));
        // 获取微调列表
        System.out.println("获取微调列表：" + OpenAiUtils.listFineTunes());
        // 获取微调信息
        System.out.println("获取微调信息：" + OpenAiUtils.retrieveFineTune(""));
        // 取消微调
        System.out.println("取消微调信息：" + OpenAiUtils.cancelFineTune(""));
        // 列出微调事件
        System.out.println("列出微调事件：" + OpenAiUtils.listFineTuneEvents(""));
        // 删除微调
        System.out.println("删除微调信息：" + OpenAiUtils.deleteFineTune(""));
    }

    @GetMapping("/files")
    @NoAuth
    @ApiOperation(value = "", hidden = true)
    public void files() {
        // 上传文件
        System.out.println("上传文件信息：" + OpenAiUtils.uploadFile("assistants", PATH));
        // 获取文件列表
        System.out.println("文件列表：" + OpenAiUtils.listFiles());
        // file-N15KLUVcePMP5bWQd10FjsGB
        // https://api.openai.com/v1/files/{file_id}/content
    }

    @Autowired
    private UserPromptService userPromptService;

    @GetMapping("/prompt")
    @ApiOperation("loadCookie")
    public List<String> midJourneyPromptWords(String message, MjPrompt promptType) {
        String role = RoleEnum.USER.getRoleName();
        //String content="你现在是midjourney绘画提示词专家,现在帮我生成一段关于'"+message +"'的midjourney提示描述词,要求描述细致,字数不少于300:";
        //  String content="作为一个Midjourney绘画提示词专家，我需要你生成一段详细描述关于'" + message + "'的绘画提示。这段描述应该非常细致，充满创意，至少包含200字，帮助画家捕捉到主题的精髓。不需要解释,我需要把返回值直接发给midJourney";
        if (promptType == null){
            promptType= MjPrompt.MJ_PROMPT;
        }
        return userPromptService.midJourneyPromptWords(message,promptType);

    }


    @PostMapping("/promptWords")
    @ApiOperation("loadCookie")
    public Page<UserPromptVo> findPrompt(@RequestBody BasePage page) {
        return userPromptService.findPrompt(page);

    }


    @Autowired
    private TranslateService translateService;

    @GetMapping("test")
    @NoAuth
    public void test(HttpServletResponse response){
       // System.out.println("translateService.translateToChinese(realContent) = " + translateService.translateToChinese("This image features a person seated in front of a background that has vertical lines of calligraphy or decorative script The person is wearing what appears to be traditional or formal attributes, with a white block feature long, sheet sleeps and a high neckline, completed by an orange, full length red skin with detailed gold embroidery that may report flowers or a traditional design The individual's appearance, along with the style of clothing, suggestions influences from East Asian fashion - potentially traditional Korean handbook The overall setting and the person's pose and expression create a series and elephant atmosphere"));
       // System.out.println("translateService.translateToChinese(realContent) = " + translateService.translateToEnglish("This image features a person seated in front of a background that has vertical lines of calligraphy or decorative script The person is wearing what appears to be traditional or formal attributes, with a white block feature long, sheet sleeps and a high neckline, completed by an orange, full length red skin with detailed gold embroidery that may report flowers or a traditional design The individual's appearance, along with the style of clothing, suggestions influences from East Asian fashion - potentially traditional Korean handbook The overall setting and the person's pose and expression create a series and elephant atmosphere"));
        UserTalkReq userTalkReq = new UserTalkReq();
        ChatImageBo.OpenaiContent openaiContent = new ChatImageBo.OpenaiContent();
        openaiContent.setType("text");
        openaiContent.setText("What’s in this image?");
        ArrayList<ChatImageBo.OpenaiContent> openaiContents = new ArrayList<>();
        openaiContents.add(openaiContent);

        ChatImageBo.OpenaiContent openaiImageContent = new ChatImageBo.OpenaiContent();
        openaiImageContent.setType("image_url");
        openaiImageContent.setImageUrl(new ChatImageBo.ImageUrl(
        "https://mrhe-ai-test.oss-cn-shenzhen.aliyuncs.com/test/base64_2.jpg?Expires=1709602258&OSSAccessKeyId=TMP.3KgtzQVTXYQZSc6J5bgSPdToy6BeBCoNxgL4S7y8BQ9Pc6p9HDBfGguMxpPbmLK6939CL7HECBpqZLVDoSPtgk7gq5XzgL&Signature=w1ew7E3tT2JolKZsBe%2FOaqcHkmE%3D"
        ));
        openaiContents.add(openaiImageContent);
        userTalkReq.setMessage(JSONObject.toJSONString(openaiContents));
        userTalkReq.setRobotId("11");
        ThreadLocalContext.setUserLoginInfo(ThreadLocalContext.getUserLoginInfo());
        userTalkReq.setUserId(ThreadLocalContext.getUserId());

        try {
            chat3Service.talkVue(userTalkReq, response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}